package org.grow.actor.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.grow.actor.dao.MaterialMapper;
import org.grow.actor.domain.Material;
import org.grow.actor.domain.MaterialDto;
import org.grow.actor.domain.MaterialQC;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * @Author: xwg
 * @CreateDate: 2023/8/18
 */

@RestController
@RequestMapping("/material")
public class MaterialController {

    @Autowired
    private MaterialMapper materialMapper;

    @PostMapping("/query")
    public IPage<Material> query(@RequestBody MaterialQC materialQC) {
        return materialMapper.dynamicQuery(Page.of(materialQC.getPageNum(), materialQC.getPageSize()),
                materialQC);
    }

    //    multiple-part/form-data
//    @PostMapping("/insert")
    @PostMapping(value = "/insert", consumes = "multipart/form-data")
    public Material insert(MaterialDto materialDto) {
        System.out.println(materialDto);
        MultipartFile pic = materialDto.getPic();
        System.out.println(pic.getOriginalFilename());
        System.out.println(pic.getName());
        Material material = new Material();
//        material.setMaterialType(materialDto.getMaterialType());
        BeanUtils.copyProperties(materialDto, material);
        String code = "MH" + System.currentTimeMillis();
        material.setMaterialCode(code);


//        String destFile = code+".jpg";
//        获取上传文件的扩展名并组成新名字。
        String originalFilename = pic.getOriginalFilename();
        String destFile = code + originalFilename.substring(originalFilename.lastIndexOf('.'));


        String destPath = "/home/xieweig/coping/pic/" + destFile;
        System.out.println(destPath);
        try {
            pic.transferTo(Paths.get(destPath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        material.setPicUrl(destFile);
        materialMapper.insert(material);
        return material;
    }
}
